package org.springframework.session.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.util.Assert;

public class SpringSessionBackedSessionRegistry<S extends Session> implements SessionRegistry {

	private final FindByIndexNameSessionRepository<S> sessionRepository;

	public SpringSessionBackedSessionRegistry(FindByIndexNameSessionRepository<S> sessionRepository) {
		Assert.notNull(sessionRepository, "sessionRepository cannot be null");
		this.sessionRepository = sessionRepository;
	}

	@Override
	public List<Object> getAllPrincipals() {
		throw new UnsupportedOperationException("SpringSessionBackedSessionRegistry does "
				+ "not support retrieving all principals, since Spring Session provides "
				+ "no way to obtain that information");
	}

	@Override
	public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
		Collection<S> sessions = this.sessionRepository.findByPrincipalName(name(principal)).values();
		List<SessionInformation> infos = new ArrayList<>();
		for (S session : sessions) {
			if (includeExpiredSessions || !Boolean.TRUE.equals(session.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) {
				infos.add(new SpringSessionBackedSessionInformation<>(session, this.sessionRepository));
			}
		}
		return infos;
	}

	@Override
	public SessionInformation getSessionInformation(String sessionId) {
		S session = this.sessionRepository.findById(sessionId);
		if (session != null) {
			return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository);
		}
		return null;
	}

	@Override
	public void refreshLastRequest(String sessionId) {
	}

	@Override
	public void registerNewSession(String sessionId, Object principal) {
	}

	@Override
	public void removeSessionInformation(String sessionId) {
	}

	protected String name(Object principal) {
		// We are reusing the logic from AbstractAuthenticationToken#getName
		return new TestingAuthenticationToken(principal, null).getName();
	}
}
